package com.zhm.demo.security;


import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.pf4j.util.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败处理类 返回未授权
 *
 * @author ruoyi
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {

        // 检查是否是 404 错误
        if (request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) != null) {
            int statusCode = (int) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                // 如果是 404，直接返回 404 响应
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
                return;
            }
        }

        int code = HttpServletResponse.SC_FORBIDDEN;
        String msg = StringUtils.format("请求访问：{}，自定义认证失败，无法访问系统资源", e.getMessage());
        response.getWriter().write("{\"code\":" + code + ",\"msg\":\"" + msg + "\"}");
    }
}

